package com.momoauth.gateway.exception;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.momoauth.gateway.enumeration.CustomExceptionEnum;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;

@Component
public class SentinelExceptionHandler implements BlockRequestHandler {

    @Override
    public Mono<ServerResponse> handleRequest(
            ServerWebExchange exchange,
            Throwable throwable
    ) {
        HashMap<String, Object> map = new HashMap<>();
        CustomExceptionEnum exceptionEnum = CustomExceptionEnum.OVERLOAD;
        // 服务限流响应
        if (throwable instanceof FlowException) {
            map.put("code", exceptionEnum.getCode());
            map.put("msg", exceptionEnum.getMsg());
        }
        // 服务降级响应
        else if (throwable instanceof DegradeException) {
            map.put("code", exceptionEnum.getCode());
            map.put("msg", exceptionEnum.getMsg());
        }
        // 返回自定义响应信息
        return ServerResponse.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(map));
    }
}
